const httpProxy = require('http-proxy');
const http = require('http');
const localtunnel = require('localtunnel');
const Tunnel = require('localtunnel/lib/Tunnel');
const util = require('util');
const ping = require('ping');
const log = require('book');
const config = require('config');
const anycall = require('anycall');

let target = '';

const port = config.get('port');
const host = config.get('host');
const proxy = httpProxy.createProxyServer({});


const server = http.createServer(async (req, res) => {
  if (!target) {
    target = await getTunnel();
  } else {
    const probe = await ping.promise.probe(target, { timeout: 5 });
    if (!probe) {
        target = await getTunnel();
    }
  }

  proxy.web(req, res, {
    target,
  });
});


server.listen('8179', host, (err) => {
  console.log('proxy server listen on 8179');
});
server.on('error', (err) => {
  log.error('Warning server error~~!!', err.msg);
});
server.on('close', () => {
  log.error('Warning server close~~!!');
});


const getTunnel = (port = '2345') => {
  try {
    const opt = {
      port,
    };

    return new Promise((resolve, reject) => {
      localtunnel(port, opt, function(err, tunnel) {
        if (err) {
            return reject(err);
        }

        console.log('your url is: %s', tunnel.url);

        return resolve(tunnel.url)
      });
    });
  } catch (err) {
    log.error(err);

    return false;
  }
};